#include<stdio.h>
#include "../include/BST.h"


#define ERR_VFS_EXPORTFILE_00 "VFS_INSUFFICIENT_ARGUMENTS"// error 4
#define ERR_VFS_EXPORTFILE_01 "CANNOT_FIND_SOURCEFILE"
#define ERR_VFS_EXPORTFILE_02 "CANNOT_CREATE_OUTPUTFILE"
#define ERR_VFS_EXPORTFILE_03 "CANNOT_EXPORT_DIR"

int export_file(char *filePath, char *outputfile)
{

	//printf("\n**In exportfile**\n");

    FILE *fp = fopen(outputfile, "w");

    int blockNumr,file_offset=0;
    char readChars,ch;

    if(outputfile==NULL)
	{
        return 2;
	}
    else if(filePath == NULL)
	{
		return 4;//
	}
    else if(fp == NULL)
	{
		return 2;
	}
    else
    {
        fd *searchedFile = bstSearchNode(&bstRoot, filePath);
	

        if(searchedFile == NULL)
		{
			return 1;
		}
        else if (searchedFile->fileType == 'D')
        {
		return 3;
	}
	else
	{

            blockNumr = searchedFile->blockNum;
          //  printf("\nBlock number=%d\n",blockNumr);
	
		

            FILE *fptr=fopen(header.fileSystemLabel,"rb");
            if(fptr==NULL)
			{
				return 2;
			}
			else
			{

				while(ch!='!')
						{
							fread(&ch,sizeof(ch),1,fptr);
							file_offset++;

						}

				fseek(fptr,(file_offset+(blockNumr*1024)),SEEK_SET);

				char buffer[1024];

				fread(buffer,(1024*sizeof(char)),1,fptr);
				//fwrite(buffer,(1024*sizeof(char)),1,fp);

				int i;
				
				for(i=0;(buffer[i]!=-1)&&(i<1024);i++)
				{
					fputc(buffer[i], fp);
				}
				
				


			}
		fclose(fptr);


        }


    }

fclose(fp);

return 0;
}

